package cc.vicp.djx314.starfood.web.security;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.Assert;

/**
 * 权限不足时根据不同的url前缀跳转到不同的页面
 * @author 水山清风
 *
 */
public class LoginUrlEntryPoint implements AuthenticationEntryPoint {
	/**
	 * url映射，由Ioc注入
	 */
	private Properties urlMapping;
	/**
	 * 默认的登陆url
	 */
	private String defaultRedirect;

	/**
	 * bean后处理器，判断属性是否为空
	 * @throws Exception
	 */
	@PostConstruct
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(urlMapping, "没有urlMapping对象，请用setCache(urlMapping)创建它！");
		Assert.notNull(defaultRedirect, "没有defaultRedirect对象，请用setCache(defaultRedirect)创建它！");
	}

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		String targetUrl = null;
		String url = request.getRequestURI();
		String contextUrl = request.getContextPath();

		Enumeration<?> enu = urlMapping.propertyNames();
		while (enu.hasMoreElements()) {
			String key = (String) enu.nextElement();
			String urlKey = contextUrl + key;
			if (url.startsWith(urlKey)) {
				//未登录而访问后台受控资源时，跳转到后台登录页面
				targetUrl = contextUrl + urlMapping.getProperty(key);
				break;
			}
		}

		if(targetUrl == null){
			targetUrl = request.getContextPath() + defaultRedirect;
		}
		response.sendRedirect(targetUrl);
	}

	/**
	 * 设置urlMapping
	 * @param urlMapping
	 */
	public void setUrlMapping(Properties urlMapping) {
		this.urlMapping = urlMapping;
	}
	/**
	 * 设置defaultRedirect
	 * @param defaultRedirect
	 */
	public void setDefaultRedirect(String defaultRedirect) {
		this.defaultRedirect = defaultRedirect;
	}
}